<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加商品分类区域 -->
      <el-row :gutter="20">
        <el-col :span="1">
          <el-button type="primary" @click="showCatdialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 树形表格 -->
      <tree-table
        class="treeTable"
        ref="treeTableRef"
        :data="catList"
        :columns="columns"
        show-index
        border
        :show-row-hover="false"
        tree-type
        :expand-type="false"
        :selection-type="false"
        index-text="#"
      >
        <!-- 是否有效列 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-show="!scope.row.cat_deleted"></i>
          <i class="el-icon-error" v-show="scope.row.cat_deleted"></i>
        </template>
        <!-- level排序列 -->
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level===1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <!-- 删除编辑操作列 -->
        <template slot="edit" slot-scope="scope">
          <el-button type="primary" 
                     class="el-icon-edit" 
                     size="small"
                     @click="showEditDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" 
                     class="el-icon-delete" 
                     size="small"
                     @click="delCat(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加分类对话框区域 -->
    <el-dialog title="添加分类" 
               :visible.sync="addCatdialogVisible" 
               width="50%"
               @close="addCatDialogClosed">
      <!-- 主体内容区域 -->
      <el-form :model="addForm" 
               :rules="addFormRules" 
               ref="addFormRef" 
               label-width="80px ">
        <!-- 分类名称 -->
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <!-- 父级分类 -->
        <el-form-item label="父级分类">
          <el-cascader
            :options="catOptions"
            :props="catProps"
            v-model="catValue"
            @change="catCasChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCatdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑商品分类对话框区域 -->
    <el-dialog title="编辑分类" 
               :visible.sync="editCatdialogVisible" 
               width="50%">
      <!-- 主体内容区域 -->
      <el-form :model="editForm" 
               :rules="editFormRules" 
               ref="editFormRef" 
               label-width="80px ">
        <!-- 分类名称 -->
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCatdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCat">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询商品分类参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类的数据列表
      catList: [],
      // 总数据条数
      total: 0,
      // 表格各列的配置
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
          width: '400px'
        },
        {
          label: '是否有效',
          // 将当前列定义成模板列
          type: 'template',
          // 表示当前这一列使用模板名称
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          // 表示当前这一列使用模板名称
          template: 'level'
        },
        {
          label: '操作',
          type: 'template',
          template: 'edit'
        }
      ],
      // 显示添加分类对话框
      addCatdialogVisible: false,
      // 添加的分类信息
      addForm: {
        cat_name: '',
        cat_pid: 0,
        cate_level: 0
      },
      //添加商品分类规则验证
      addFormRules: {
        cat_name:[
          { required: true, message: '请输入分类名称', trigger: 'blur' }, 
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' } 
        ]
      },
      // 下拉框选项数据源
      catOptions: [],
      // 下拉框绑定值，id
      catValue: [],
      // 级联选择器的配置项
      catProps: {
        expandTrigger: 'hovel',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 编辑分类是否可见
      editCatdialogVisible:false,
      // 编辑分类表单
      editForm:{
        cat_name:''
      },
      //编辑商品分类规则验证
      editFormRules: {
        cat_name:[
          { required: true, message: '请输入分类名称', trigger: 'blur' }, 
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' } 
        ]
      },
    }
  },
  created() {
    this.getCatList()
  },
  methods: {
    // 获取商品分类数据
    async getCatList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        this.$message.error('更新商品分类列表失败！')
      }
      this.catList = res.data.result
      this.total = res.data.total
      // console.log(res)
    },
    // 监听pagesize的改变
    handleSizeChange(newsize) {
      // console.log(newsize)
      this.queryInfo.pagesize = newsize
      this.getCatList()
    },
    // 监听当前页面的改变
    handleCurrentChange(newpage) {
      // console.log(newpage)
      this.queryInfo.pagenum = newpage
      this.getCatList()
    },
    // 获取级联选择器中的商品分类数据
    async showCatdialog() {
      this.addCatdialogVisible = true
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据列表失败！')
      }
      this.catOptions = res.data
      console.log(res.data)
    },
    // 级联选择器选择发生改变
    catCasChange() {
      if(this.catValue.length > 0){
        this.addForm.cat_pid = this.catValue[this.catValue.length - 1]
        this.addForm.cate_level = this.catValue.length
        return
      }else{
        this.addForm.cat_pid = 0
        this.addForm.cate_level = 0
      }
      console.log(this.catValue)
    },
    // 添加分类
    addCate(){
      this.$refs.addFormRef.validate(async validate => {
        if(!validate) return
        const {data:res} = await this.$http.post('categories', this.addForm)
        if(res.meta.status !== 201){
          return this.$message.error('添加商品分类失败！')
        }
        this.getCatList()
        this.$message.success('添加商品分类成功！')
        this.addCatdialogVisible = false
      })
    },
    // 清空表单数据
    addCatDialogClosed(){
      // this.addForm.cat_name = ''
      this.addForm.cat_pid = 0
      this.addForm.cate_level = 0
      this.catValue = []
      this.$refs.addFormRef.resetFields()
    },
    // 显示编辑分类对话框
    async showEditDialog(id){
      const {data:res} = await this.$http.get('categories/' + id)

      if(res.meta.status !== 200){
          return this.$message.error('添加商品分类失败！')
      }
      this.editForm = res.data
      this.editCatdialogVisible = true
    },
    // 编辑分类
    editCat(){
      this.$refs.editFormRef.validate(async valid => {
        if(!valid) return
        const {data:res} =  await this.$http.put('categories/' + this.editForm.cat_id, {
          cat_name:this.editForm.cat_name
        })
        // console.log(this.editForm)
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('编辑商品分类成功！')
        this.editCatdialogVisible = false
        this.getCatList()
      })
    },
    // 删除商品分类
    async delCat(id){
      const result = await this.$confirm('此操作将永久删除分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => {
          return error
        })
        if(result === 'confirm'){
          const {data:res} = await this.$http.delete('categories/' + id)
          if(res.meta.status !== 200){
           return this.$message.error('删除商品分类失败！')
          }
          this.$message.success('删除商品分类成功！')
          this.getCatList()
        }
      console.log(result)
    }
  }
}
</script>

<style lang="less" scoped>
.el-icon-success {
  color: lightgreen;
}
.el-icon-error {
  color: red;
}
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}



</style>
